package com.jiajia.study.product.exception;

import com.jiajia.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjiajia
 * @date 2025/6/11 17:19
 */

/**
 * 这里需要使用 RestControllerAdvice，用ControllerAdvice会再被加一层
 */
@RestControllerAdvice(basePackages = "com.jiajia.study.product")
@Slf4j
public class ProductExceptionControllerAdvice {
    /**
     * 参数校验不通过异常处理
     * @param exception 异常
     * @return          统一异常返回结果
     */
    @ExceptionHandler(Exception.class)
    public R handleInvalidException(MethodArgumentNotValidException exception) {
        Map<String,String> errorMap = new HashMap<>();

        BindingResult bindingResult = exception.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        fieldErrors.forEach(item ->{
                    String field = item.getField();
                    String defaultMessage = item.getDefaultMessage();
                    errorMap.put(field,defaultMessage);
                });
        log.error("ProductExceptionControllerAdvice#handleInvalidException ====> 数据校验出现问题:{},异常类为:{}",exception.getMessage(),exception.getClass());
        return R.error(400, "参数校验出错").put("data",errorMap);

    }
}
